package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.FamilyListVo;
import com.zzyl.nursing.vo.FamilyMemberListVo;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 家人服务实现类
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{

    @Autowired
    private WechatService wechatService;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private IElderService elderService;
    @Autowired
    private IFamilyMemberService familyMemberService;
    @Autowired
    private IFamilyMemberElderService familyMemberElderService;
    @Autowired
    private IDeviceDataService deviceDataService;

    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    /**
     * 微信登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {
        //1.根据code调用微信api获取apenId
        String openid = wechatService.getOpenid(dto.getCode());

        //2.根据openId查询数据库获取用户信息family_member表
        FamilyMember familyMember = this.getOne(Wrappers.<FamilyMember>lambdaQuery()
                .eq(FamilyMember::getOpenId, openid));

        //3.判断用户信息是否存在，如果不存在，则新增family_member表
        if (ObjectUtils.isEmpty(familyMember)){
            familyMember=FamilyMember.builder().openId(openid).build();

        }

        //4.调用微信api获取用户绑定手机号
        String phone = wechatService.getPhone(dto.getPhoneCode());
        redisTemplate.opsForValue().set("wx:phone", phone);

        //5.新增或者修改family_member表数据
        saveOrUpdateFamilyMember(familyMember,phone);
//        update(Wrappers.<FamilyMember>lambdaUpdate().eq(FamilyMember::getId,phone));


        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId",familyMember.getId());
        claims.put("nickName",dto.getNickName());
        //6.将用户id存入token中，并返回数据给前端
        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(familyMember.getName());
        loginVo.setToken(token);


        return loginVo;
    }

    /**
     * 新增或修改数据
     * @param familyMember
     * @param phone
     */
    private void saveOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //如果手机号不相等，就修改
//        if (familyMember.getPhone().equals(phone)){
        if (ObjectUtil.notEqual(phone, familyMember.getPhone())) {
                familyMember.setPhone(phone);
        }

        if (ObjectUtils.isEmpty(familyMember.getId())){
            //新增
            //生成用户名
            familyMember.setName(DEFAULT_NICKNAME_PREFIX.get((int) (Math.random()*DEFAULT_NICKNAME_PREFIX.size()))+ StringUtils.substring(familyMember.getPhone(), 7));
            save(familyMember);
        }

        //修改
        updateById(familyMember);
    }

    /**
     * 获取当前登录用户的手机号
     * @return 手机号
     */
    private String getCurrentUserPhone() {
        return (String) redisTemplate.opsForValue().get("wx:phone");
    }
    /*
     * 绑定家人
     * */
    @Override
    public void add(FamilyDto familyDto) {
        // 调用获取当前用户的手机号方法从redis中获取当前登录用户的手机号
        String phone = getCurrentUserPhone();
        // 根据身份证号查询老人信息
        Elder elder = elderService.getOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, familyDto.getIdCard()));
        // 根据手机号查询家人信息
        FamilyMember familyMember = familyMemberService.getOne(Wrappers.<FamilyMember>lambdaQuery()
                .eq(FamilyMember::getPhone, phone));
        // 构建家人与老人的关联关系对象
        FamilyMemberElder familyMemberElder= FamilyMemberElder.builder()
                .familyMemberId(Integer.valueOf(familyMember.getId() + ""))
                .elderId(Integer.valueOf(elder.getId() + ""))
                .build();
        familyMemberElder.setRemark(familyDto.getRemark());
        // 保存家人与老人的关联关系
        familyMemberElderService.save(familyMemberElder);
    }

    /*
     * 查询家人列表
     * */
    @Override
    public List<FamilyListVo> listFamilyMembers() {
        // 调用获取当前用户的手机号方法从redis中获取当前登录用户手机号，并查询对应的家庭成员信息
        String phone = getCurrentUserPhone();
        FamilyMember familyMember =familyMemberService.getOne(Wrappers.<FamilyMember>lambdaQuery()
                .eq(FamilyMember::getPhone, phone));
        // 根据家庭成员ID查询关联的老人信息列表
        List<FamilyListVo> familyMemberlist =  familyMemberMapper.listFamilyMembers(familyMember.getId());
        //返回家人列表集合
        return familyMemberlist;
    }

    /*
    * 分页查询家人列表
    * */
    @Override
    public List<FamilyMemberListVo> findByPage(Integer pageNum, Integer pageSize) {
        // 设置分页参数
        PageHelper.startPage(pageNum,pageSize);
        // 调用获取当前用户的手机号方法从redis中获取当前登录用户手机号，并查询对应的家庭成员信息
        String phone = getCurrentUserPhone();
        FamilyMember familyMember =familyMemberService.getOne(Wrappers.<FamilyMember>lambdaQuery()
                .eq(FamilyMember::getPhone, phone));
        // 根据家庭成员ID分页查询家人列表
        List<FamilyMemberListVo> list= familyMemberMapper.findByPage(familyMember.getId());
        //返回家人列表集合
        return list;
    }

    /**
     * 查询健康数据
     *
     * @param deviceDto
     */
    @Override
    public Map<String, HealthDataDto> selectHealthData(DeviceDto deviceDto) {
        return deviceDataService.selectHealthData(deviceDto);
    }

    /**
     * 按天统计查询指标数据
     *
     * @param queryDeviceDataByDayDto 查询参数
     * @return
     */
    @Override
    public List<Map<String, Object>> queryDeviceDataListByDay(QueryDeviceDataByDayDto queryDeviceDataByDayDto) {
        //调用设备数据业务层，查询设备数据信息
        return deviceDataService.queryDeviceDataListByDay(queryDeviceDataByDayDto);
    }

    /**
     * 按周统计查询指标数据
     *
     * @param queryDeviceDataByDayDto
     */
    @Override
    public List<Map<String, Object>> queryDeviceDataListByWeek(QueryDeviceDataByDayDto queryDeviceDataByDayDto) {
        //调用设备数据业务层，查询设备数据信息
        return deviceDataService.queryDeviceDataListByWeek(queryDeviceDataByDayDto);
    }
    /*
    * 解除绑定
    * */
    @Override
    public void deleteById(Long id) {
        familyMemberElderService.remove(Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getId,id));
    }
}
